<template>
  <div>
    <!-- <div v-if="state===1">认证页面跳转中...</div> -->
    <!-- <div v-if="state===2">认证成功，正在为您跳转至首页</div> -->
    <!-- <div v-if="state===3"> -->
    <!-- 登录失败，点击<a href="/">这里</a>重试 -->
    <!-- </div> -->
    <div class="exception-page" :style="`min-height: ${minHeight}`">
      <div class="img">
        <img src="https://gw.alipayobjects.com/zos/rmsportal/KpnpchXsobRgLElEozzI.svg" />
      </div>
      <div class="content" v-if="state===1">
        <h3>认证页面跳转中...</h3>
      </div>
      <div class="content" v-if="state===2">
        <h3>认证成功，正在为您跳转至首页</h3>
      </div>
      <div class="content" v-if="state===3">
        <h3>登录失败</h3>
        <div class="desc">抱歉，登录失败</div>
        <div class="action">
          <a-button type="primary" href="/">点击重试</a-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapActions, mapGetters, mapState } from 'vuex'
export default {
  name: 'LoginSSO',
  components: { },
  data() {
    return {
      state: 1
    }
  },
  computed: {
    ...mapGetters(['token']),
    ...mapState('setting', ['thirdPlatformType', 'ssoLoginUrl', 'ssoClientId', 'ssoLocalUrl', 'pageMinHeight']),
    minHeight() {
      return this.pageMinHeight ? this.pageMinHeight + 'px' : '100vh'
    }
  },
  methods: {
    ...mapActions('account', ['Login']),
    async getAuthCode() { // 根据类型获取三方用户权限
      const appType = this.thirdPlatformType
      if (appType === 'feishu') {
        return this.feishu()
      } else if (appType === 'wechat') {
        return this.wechat()
      } else if (appType === 'dingtalk') {
        return this.dingding()
      } else if (appType === 'oauth') {
        return this.oauth()
      } else if (appType === 'MSAL') {
        return this.msal()
      }
    },
    feishu() { // 获取飞书用户权限，待实现

    },
    wechat() { // 获取微信用户权限，待实现

    },
    async oauth() { // 获取三方登录用户权限
      const code = this.getUrlKey('code')
      if (code) {
        return code
      } else {
        const redirect_uri = encodeURI(`${this.ssoLocalUrl}/loginsso`)
        location.href = `${this.ssoLoginUrl}?client_id=${this.ssoClientId}&response_type=code&scope=openid&redirect_uri=${redirect_uri}&state=70641054-0d46-41d6-9b57-97a14dfd14d1&nonce=a9ac2e26-68b4-44e1-8c20-8d98ae389175&prompt=select_account&response_mode=query`
      }
    },
    async dingding() { // 获取钉钉用户权限
      return new Promise((resolve, reject) => {
        window.dd.runtime.permission.requestAuthCode({
          corpId: '',
          onSuccess: function(result) {
            resolve(result.code)
          },
          onFail: function(err) {
            console.log(err)
            reject(err)
          }
        })
      })
    },
    async msal() {
      try {
        const myMSALObj = new window.msal.PublicClientApplication({
          auth: {
            // // 'Application (client) ID' of app registration in Azure portal - this value is a GUID
            clientId: this.ssoClientId,
            // // Full directory URL, in the form of https://login.microsoftonline.com/<tenant-id>
            authority: this.ssoLoginUrl,
            // // Full redirect URL, in form of http://localhost:3000
            redirectUri: `${this.ssoLocalUrl}`
            // 'Application (client) ID' of app registration in Azure portal - this value is a GUID
            // clientId: 'eb9d8895-0813-4487-997f-e68dbc4cf454',
            // Full directory URL, in the form of https://login.microsoftonline.com/<tenant-id>
            // authority: 'https://login.microsoftonline.com/common',
            // Full redirect URL, in form of http://localhost:3000
            // redirectUri: 'http://localhost:8081'
          },
          cache: {
            cacheLocation: 'sessionStorage', // This configures where your cache will be stored
            storeAuthStateInCookie: false // Set this to "true" if you are having issues on IE11 or Edge
          },
          system: {
            loggerOptions: {
              loggerCallback: (level, message, containsPii) => {
                if (containsPii) {
                  return
                }
                switch (level) {
                  case window.msal.LogLevel.Error:
                    console.error(message)
                    return
                  case window.msal.LogLevel.Info:
                    console.info(message)
                    return
                  case window.msal.LogLevel.Verbose:
                    console.debug(message)
                    return
                  case window.msal.LogLevel.Warning:
                    console.warn(message)
                    return
                }
              }
            }
          }
        })
        const response = await myMSALObj.loginPopup({
          scopes: ['User.Read']
        })
        console.log('response', response)
        return response.account.username
      } catch (error) {
        console.error(error)
      }
    },
    async doLogin(code) {
      return this.Login({
        authCode: code,
        thirdPlatformType: this.thirdPlatformType
      }).then(res => {
        if (res.success) {
          this.toPage()
          this.state = 2
        } else {
          this.$message.warning('登录失败，请重试')
          this.state = 3
        }
      })
    },
    toPage() {
      this.$router.push({ path: '/' })
    },
    getUrlKey(name) {
      // eslint-disable-next-line no-sparse-arrays
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
    }
  },
  async mounted() {
    try {
      if (this.token) {
        this.toPage()
        return
      }
      // 获取第三方用户权限code
      const code = await this.getAuthCode()
      console.log('code', code)
      if (code) {
        // 系统自动登录
        await this.doLogin(code)
      }
      // else {
      //   this.$message.warning('登录失败，请重试')
      // }
    } catch (e) {
      // TODO handle the exception
      this.state = 3
      this.$message.warning('登录失败，请重试')
    }
  }
}
</script>
<style lang="less" scoped>
  .exception-page{
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: @base-bg-color;
    .img{
      padding-right: 52px;
      zoom: 1;
      img{
        max-width: 430px;
      }
    }
    .content{
      h3{
        color: #434e59;
        font-size: 40px;
        font-weight: 600;
        line-height: 40px;
        margin-bottom: 24px;
      }
      .desc{
        color: @text-color-second;
        font-size: 20px;
        line-height: 28px;
        margin-bottom: 16px;
      }
    }
  }

</style>
